/*
* Copyright 2004-2005 mbsx@seznam.cz
* All Rights Reserved.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Threading;
using System.Globalization;
using System.Drawing.Printing;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace DeskNotes
{
	/// <summary>
	/// Summary description for NoteForm.
	/// </summary>
	public class NoteForm : System.Windows.Forms.Form
	{

		public delegate void ElapsedInvoke();
		internal ElapsedInvoke invocation;

        private System.ComponentModel.IContainer components;
		private Note note;
        private System.Windows.Forms.FontDialog fontDialog;
		private System.Windows.Forms.ToolTip toolTip;
		private int mouseX, mouseY;
		private Cursor beforeMoveCursor;
		//flags for processing between different but related events.
		private bool ControlDown = false;
		private bool WasMoved = false;
		private bool textChanged = false;
        private bool FormResized = false;
        private bool ReadyForMouse = false;
        private System.Windows.Forms.ColorDialog colorDialog;
        internal System.Timers.Timer timer1;
		
        private bool archiving = false;
		private bool dragging = false;
		//private int mouseX, mouseY;
        private Rectangle dragRect;
		private string normalToolTip;
		private ListViewItem remindersItem = null;
		internal bool sendBack = true;
        private int borderSize;
		// True if this desknote was created over topmost desknote. 
		// Is reset when this desknotes deactivates.
        internal bool topMostViolated = false;
        private ToolStrip toolStripRTF;
        private ToolStripButton btnBold;
        private ToolStripButton btnItalic;
        private ToolStripButton btnBullet;
        private ToolStripButton btnStrike;
        private ToolStripSeparator toolStripSeparator1;
        private ToolStripButton btnIndentRight;
        private ToolStripButton btnIndentLeft;
        private ToolStripContainer toolStripContainer1;
        private TableLayoutPanel tableLayoutPanel;
        private FlowLayoutPanel panel;
        private PictureBox clockPicture;
        internal Label alarmTime;
        internal RichTextBox txtNote;
        private ToolStripSeparator toolStripSeparator2;
        private ToolStripSeparator toolStripSeparator3;
        private ToolStripButton btnFont;
        private ToolStripButton btnBackColor;
        private ToolStripButton btnUnderline;
        private ContextMenuStrip mainMenu;
        private ToolStripMenuItem alwaysOnTopStripMenuItem;
        private ToolStripMenuItem hideStripMenuItem;
        private ToolStripMenuItem newStripMenuItem;
        private ToolStripMenuItem saveStripMenuItem;
        private ToolStripMenuItem archiveStripMenuItem;
        private ToolStripMenuItem removeStripMenuItem;
        private ToolStripMenuItem emailStripMenuItem;
        private ToolStripSeparator toolStripSeparator4;
        private ToolStripMenuItem copyToOutlookStripMenuItem;
        private ToolStripSeparator toolStripSeparator5;
        private ToolStripMenuItem reminderStripMenuItem;
        private ToolStripMenuItem removeReminderStripMenuItem;
        private ToolStripMenuItem insertTimestampStripMenuItem;
        private ToolStripSeparator toolStripSeparator6;
        private ToolStripMenuItem formattingStripMenuItem;
        private ToolStripMenuItem opacityStripMenuItem;
        private ToolStripMenuItem printStripMenuItem;
        private ToolStripSeparator toolStripSeparator7;
        private ToolStripMenuItem exitStripMenuItem;
        internal NoteForm myCopy = null;

        static int INDENT = 10;
						

		public Note NoteData
		{
			set 
			{
				note = value;
				note.MyForm = this;
				SetTimer();
				SetAlarmToolbar();
			}
			get 
			{
				return note;
			}
		}

		
		public NoteForm()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
            
			normalToolTip = toolTip.GetToolTip(txtNote);
			invocation = new ElapsedInvoke(Alarmed);
			//this.TopLevel = true;
			
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if(components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(NoteForm));
            this.toolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
            this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel();
            this.txtNote = new System.Windows.Forms.RichTextBox();
            this.mainMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.alwaysOnTopStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.hideStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
            this.newStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.saveStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.archiveStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.removeStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.emailStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.copyToOutlookStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
            this.reminderStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.removeReminderStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.insertTimestampStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
            this.formattingStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.opacityStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.printStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
            this.exitStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.panel = new System.Windows.Forms.FlowLayoutPanel();
            this.clockPicture = new System.Windows.Forms.PictureBox();
            this.alarmTime = new System.Windows.Forms.Label();
            this.toolStripRTF = new System.Windows.Forms.ToolStrip();
            this.btnBullet = new System.Windows.Forms.ToolStripButton();
            this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.btnBold = new System.Windows.Forms.ToolStripButton();
            this.btnItalic = new System.Windows.Forms.ToolStripButton();
            this.btnStrike = new System.Windows.Forms.ToolStripButton();
            this.btnUnderline = new System.Windows.Forms.ToolStripButton();
            this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.btnIndentRight = new System.Windows.Forms.ToolStripButton();
            this.btnIndentLeft = new System.Windows.Forms.ToolStripButton();
            this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
            this.btnFont = new System.Windows.Forms.ToolStripButton();
            this.btnBackColor = new System.Windows.Forms.ToolStripButton();
            this.fontDialog = new System.Windows.Forms.FontDialog();
            this.toolTip = new System.Windows.Forms.ToolTip(this.components);
            this.colorDialog = new System.Windows.Forms.ColorDialog();
            this.timer1 = new System.Timers.Timer();
            this.toolStripContainer1.ContentPanel.SuspendLayout();
            this.toolStripContainer1.TopToolStripPanel.SuspendLayout();
            this.toolStripContainer1.SuspendLayout();
            this.tableLayoutPanel.SuspendLayout();
            this.mainMenu.SuspendLayout();
            this.panel.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.clockPicture)).BeginInit();
            this.toolStripRTF.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
            this.SuspendLayout();
            // 
            // toolStripContainer1
            // 
            // 
            // toolStripContainer1.ContentPanel
            // 
            resources.ApplyResources(this.toolStripContainer1.ContentPanel, "toolStripContainer1.ContentPanel");
            this.toolStripContainer1.ContentPanel.Controls.Add(this.tableLayoutPanel);
            resources.ApplyResources(this.toolStripContainer1, "toolStripContainer1");
            this.toolStripContainer1.Name = "toolStripContainer1";
            // 
            // toolStripContainer1.TopToolStripPanel
            // 
            this.toolStripContainer1.TopToolStripPanel.Controls.Add(this.toolStripRTF);
            // 
            // tableLayoutPanel
            // 
            resources.ApplyResources(this.tableLayoutPanel, "tableLayoutPanel");
            this.tableLayoutPanel.Controls.Add(this.txtNote, 0, 1);
            this.tableLayoutPanel.Controls.Add(this.panel, 0, 0);
            this.tableLayoutPanel.Name = "tableLayoutPanel";
            // 
            // txtNote
            // 
            this.txtNote.AcceptsTab = true;
            this.txtNote.BackColor = System.Drawing.Color.Yellow;
            this.txtNote.BorderStyle = System.Windows.Forms.BorderStyle.None;
            resources.ApplyResources(this.txtNote, "txtNote");
            this.txtNote.ContextMenuStrip = this.mainMenu;
            this.txtNote.Name = "txtNote";
            this.tableLayoutPanel.SetRowSpan(this.txtNote, 2);
            this.toolTip.SetToolTip(this.txtNote, resources.GetString("txtNote.ToolTip"));
            this.txtNote.KeyDown += new System.Windows.Forms.KeyEventHandler(this.NoteForm_KeyDown);
            this.txtNote.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MoveEnd_onMouseUp);
            this.txtNote.SelectionChanged += new System.EventHandler(this.txtNote_SelectionChanged);
            this.txtNote.LinkClicked += new System.Windows.Forms.LinkClickedEventHandler(this.txtNote_LinkClicked);
            this.txtNote.MouseMove += new System.Windows.Forms.MouseEventHandler(this.NoteForm_MouseMove);
            this.txtNote.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MoveStart_OnMouseDown);
            this.txtNote.KeyUp += new System.Windows.Forms.KeyEventHandler(this.NoteForm_KeyUp);
            // 
            // mainMenu
            // 
            this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.alwaysOnTopStripMenuItem,
            this.hideStripMenuItem,
            this.toolStripSeparator4,
            this.newStripMenuItem,
            this.saveStripMenuItem,
            this.archiveStripMenuItem,
            this.removeStripMenuItem,
            this.emailStripMenuItem,
            this.copyToOutlookStripMenuItem,
            this.toolStripSeparator5,
            this.reminderStripMenuItem,
            this.removeReminderStripMenuItem,
            this.insertTimestampStripMenuItem,
            this.toolStripSeparator6,
            this.formattingStripMenuItem,
            this.opacityStripMenuItem,
            this.printStripMenuItem,
            this.toolStripSeparator7,
            this.exitStripMenuItem});
            this.mainMenu.Name = "contextMenuStrip1";
            resources.ApplyResources(this.mainMenu, "mainMenu");
            this.mainMenu.Opening += new System.ComponentModel.CancelEventHandler(this.mainMenu_Opening);
            // 
            // alwaysOnTopStripMenuItem
            // 
            this.alwaysOnTopStripMenuItem.CheckOnClick = true;
            resources.ApplyResources(this.alwaysOnTopStripMenuItem, "alwaysOnTopStripMenuItem");
            this.alwaysOnTopStripMenuItem.Name = "alwaysOnTopStripMenuItem";
            this.alwaysOnTopStripMenuItem.Click += new System.EventHandler(this.menuAlwaysOnTop_Click);
            // 
            // hideStripMenuItem
            // 
            this.hideStripMenuItem.Name = "hideStripMenuItem";
            resources.ApplyResources(this.hideStripMenuItem, "hideStripMenuItem");
            this.hideStripMenuItem.Click += new System.EventHandler(this.menuHide_Click);
            // 
            // toolStripSeparator4
            // 
            this.toolStripSeparator4.Name = "toolStripSeparator4";
            resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
            // 
            // newStripMenuItem
            // 
            resources.ApplyResources(this.newStripMenuItem, "newStripMenuItem");
            this.newStripMenuItem.Name = "newStripMenuItem";
            this.newStripMenuItem.Click += new System.EventHandler(this.CreateNewNote);
            // 
            // saveStripMenuItem
            // 
            resources.ApplyResources(this.saveStripMenuItem, "saveStripMenuItem");
            this.saveStripMenuItem.Name = "saveStripMenuItem";
            this.saveStripMenuItem.Click += new System.EventHandler(this.menuSave_Click);
            // 
            // archiveStripMenuItem
            // 
            this.archiveStripMenuItem.Name = "archiveStripMenuItem";
            resources.ApplyResources(this.archiveStripMenuItem, "archiveStripMenuItem");
            this.archiveStripMenuItem.Click += new System.EventHandler(this.menuArchive_Click);
            // 
            // removeStripMenuItem
            // 
            resources.ApplyResources(this.removeStripMenuItem, "removeStripMenuItem");
            this.removeStripMenuItem.Name = "removeStripMenuItem";
            this.removeStripMenuItem.Click += new System.EventHandler(this.menuRemove_Click);
            // 
            // emailStripMenuItem
            // 
            this.emailStripMenuItem.Name = "emailStripMenuItem";
            resources.ApplyResources(this.emailStripMenuItem, "emailStripMenuItem");
            this.emailStripMenuItem.Click += new System.EventHandler(this.menuEmail_Click);
            // 
            // copyToOutlookStripMenuItem
            // 
            resources.ApplyResources(this.copyToOutlookStripMenuItem, "copyToOutlookStripMenuItem");
            this.copyToOutlookStripMenuItem.Name = "copyToOutlookStripMenuItem";
            this.copyToOutlookStripMenuItem.Click += new System.EventHandler(this.menuSaveInOutlook_Click);
            // 
            // toolStripSeparator5
            // 
            this.toolStripSeparator5.Name = "toolStripSeparator5";
            resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
            // 
            // reminderStripMenuItem
            // 
            resources.ApplyResources(this.reminderStripMenuItem, "reminderStripMenuItem");
            this.reminderStripMenuItem.Name = "reminderStripMenuItem";
            this.reminderStripMenuItem.Click += new System.EventHandler(this.SetAlarm);
            // 
            // removeReminderStripMenuItem
            // 
            this.removeReminderStripMenuItem.Name = "removeReminderStripMenuItem";
            resources.ApplyResources(this.removeReminderStripMenuItem, "removeReminderStripMenuItem");
            this.removeReminderStripMenuItem.Click += new System.EventHandler(this.ResetAlarm);
            // 
            // insertTimestampStripMenuItem
            // 
            this.insertTimestampStripMenuItem.Name = "insertTimestampStripMenuItem";
            resources.ApplyResources(this.insertTimestampStripMenuItem, "insertTimestampStripMenuItem");
            this.insertTimestampStripMenuItem.Click += new System.EventHandler(this.menuInsertTime_Click);
            // 
            // toolStripSeparator6
            // 
            this.toolStripSeparator6.Name = "toolStripSeparator6";
            resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
            // 
            // formattingStripMenuItem
            // 
            this.formattingStripMenuItem.Name = "formattingStripMenuItem";
            resources.ApplyResources(this.formattingStripMenuItem, "formattingStripMenuItem");
            this.formattingStripMenuItem.Click += new System.EventHandler(this.menuEdit_Click);
            // 
            // opacityStripMenuItem
            // 
            this.opacityStripMenuItem.Name = "opacityStripMenuItem";
            resources.ApplyResources(this.opacityStripMenuItem, "opacityStripMenuItem");
            this.opacityStripMenuItem.Click += new System.EventHandler(this.menuOpacity_Click);
            // 
            // printStripMenuItem
            // 
            resources.ApplyResources(this.printStripMenuItem, "printStripMenuItem");
            this.printStripMenuItem.Name = "printStripMenuItem";
            this.printStripMenuItem.Click += new System.EventHandler(this.menuPrint_Click);
            // 
            // toolStripSeparator7
            // 
            this.toolStripSeparator7.Name = "toolStripSeparator7";
            resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7");
            // 
            // exitStripMenuItem
            // 
            this.exitStripMenuItem.Name = "exitStripMenuItem";
            resources.ApplyResources(this.exitStripMenuItem, "exitStripMenuItem");
            this.exitStripMenuItem.Click += new System.EventHandler(this.Exit_Clicked);
            // 
            // panel
            // 
            resources.ApplyResources(this.panel, "panel");
            this.panel.ContextMenuStrip = this.mainMenu;
            this.panel.Controls.Add(this.clockPicture);
            this.panel.Controls.Add(this.alarmTime);
            this.panel.Name = "panel";
            this.panel.MouseMove += new System.Windows.Forms.MouseEventHandler(this.NoteForm_MouseMove);
            this.panel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MoveStart_OnMouseDown);
            this.panel.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MoveEnd_onMouseUp);
            // 
            // clockPicture
            // 
            this.clockPicture.BackColor = System.Drawing.Color.Transparent;
            this.clockPicture.ContextMenuStrip = this.mainMenu;
            resources.ApplyResources(this.clockPicture, "clockPicture");
            this.clockPicture.Name = "clockPicture";
            this.clockPicture.TabStop = false;
            this.toolTip.SetToolTip(this.clockPicture, resources.GetString("clockPicture.ToolTip"));
            // 
            // alarmTime
            // 
            resources.ApplyResources(this.alarmTime, "alarmTime");
            this.alarmTime.BackColor = System.Drawing.Color.Yellow;
            this.alarmTime.ContextMenuStrip = this.mainMenu;
            this.alarmTime.FlatStyle = System.Windows.Forms.FlatStyle.System;
            this.alarmTime.Name = "alarmTime";
            this.toolTip.SetToolTip(this.alarmTime, resources.GetString("alarmTime.ToolTip"));
            this.alarmTime.MouseMove += new System.Windows.Forms.MouseEventHandler(this.NoteForm_MouseMove);
            this.alarmTime.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MoveStart_OnMouseDown);
            this.alarmTime.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MoveEnd_onMouseUp);
            // 
            // toolStripRTF
            // 
            this.toolStripRTF.AllowItemReorder = true;
            resources.ApplyResources(this.toolStripRTF, "toolStripRTF");
            this.toolStripRTF.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.btnBullet,
            this.toolStripSeparator2,
            this.btnBold,
            this.btnItalic,
            this.btnStrike,
            this.btnUnderline,
            this.toolStripSeparator1,
            this.btnIndentRight,
            this.btnIndentLeft,
            this.toolStripSeparator3,
            this.btnFont,
            this.btnBackColor});
            this.toolStripRTF.Name = "toolStripRTF";
            this.toolStripRTF.Stretch = true;
            // 
            // btnBullet
            // 
            this.btnBullet.CheckOnClick = true;
            this.btnBullet.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnBullet, "btnBullet");
            this.btnBullet.Name = "btnBullet";
            this.btnBullet.Click += new System.EventHandler(this.btnBullet_Click);
            // 
            // toolStripSeparator2
            // 
            this.toolStripSeparator2.Name = "toolStripSeparator2";
            resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
            // 
            // btnBold
            // 
            this.btnBold.CheckOnClick = true;
            this.btnBold.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnBold, "btnBold");
            this.btnBold.Name = "btnBold";
            this.btnBold.Click += new System.EventHandler(this.btnBold_Click);
            // 
            // btnItalic
            // 
            this.btnItalic.CheckOnClick = true;
            this.btnItalic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnItalic, "btnItalic");
            this.btnItalic.Name = "btnItalic";
            this.btnItalic.Click += new System.EventHandler(this.btnItalic_Click);
            // 
            // btnStrike
            // 
            this.btnStrike.CheckOnClick = true;
            this.btnStrike.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnStrike, "btnStrike");
            this.btnStrike.Name = "btnStrike";
            this.btnStrike.Click += new System.EventHandler(this.btnStrike_Click);
            // 
            // btnUnderline
            // 
            this.btnUnderline.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnUnderline, "btnUnderline");
            this.btnUnderline.Name = "btnUnderline";
            this.btnUnderline.Click += new System.EventHandler(this.btnUnderline_Click);
            // 
            // toolStripSeparator1
            // 
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
            // 
            // btnIndentRight
            // 
            this.btnIndentRight.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnIndentRight, "btnIndentRight");
            this.btnIndentRight.Name = "btnIndentRight";
            this.btnIndentRight.Click += new System.EventHandler(this.btnIndentRight_Click);
            // 
            // btnIndentLeft
            // 
            this.btnIndentLeft.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnIndentLeft, "btnIndentLeft");
            this.btnIndentLeft.Name = "btnIndentLeft";
            this.btnIndentLeft.Click += new System.EventHandler(this.btnIndentLeft_Click);
            // 
            // toolStripSeparator3
            // 
            this.toolStripSeparator3.Name = "toolStripSeparator3";
            resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
            // 
            // btnFont
            // 
            this.btnFont.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnFont, "btnFont");
            this.btnFont.Name = "btnFont";
            this.btnFont.Click += new System.EventHandler(this.btnFont_Click);
            // 
            // btnBackColor
            // 
            this.btnBackColor.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
            resources.ApplyResources(this.btnBackColor, "btnBackColor");
            this.btnBackColor.Name = "btnBackColor";
            this.btnBackColor.Click += new System.EventHandler(this.btnBackColor_Click);
            // 
            // fontDialog
            // 
            this.fontDialog.ShowColor = true;
            // 
            // timer1
            // 
            this.timer1.AutoReset = false;
            this.timer1.SynchronizingObject = this;
            this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
            // 
            // NoteForm
            // 
            resources.ApplyResources(this, "$this");
            this.BackColor = System.Drawing.Color.Yellow;
            this.Controls.Add(this.toolStripContainer1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.SizableToolWindow;
            this.Name = "NoteForm";
            this.ShowInTaskbar = false;
            this.Deactivate += new System.EventHandler(this.NoteForm_Deactivate);
            this.Load += new System.EventHandler(this.NoteForm_Load);
            this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.MoveEnd_onMouseUp);
            this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MoveStart_OnMouseDown);
            this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.NoteForm_KeyUp);
            this.QueryContinueDrag += new System.Windows.Forms.QueryContinueDragEventHandler(this.NoteForm_QueryContinueDrag);
            this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.NoteForm_MouseMove);
            this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.NoteForm_KeyDown);
            this.toolStripContainer1.ContentPanel.ResumeLayout(false);
            this.toolStripContainer1.TopToolStripPanel.ResumeLayout(false);
            this.toolStripContainer1.TopToolStripPanel.PerformLayout();
            this.toolStripContainer1.ResumeLayout(false);
            this.toolStripContainer1.PerformLayout();
            this.tableLayoutPanel.ResumeLayout(false);
            this.mainMenu.ResumeLayout(false);
            this.panel.ResumeLayout(false);
            this.panel.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.clockPicture)).EndInit();
            this.toolStripRTF.ResumeLayout(false);
            this.toolStripRTF.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion


		private void NoteForm_Load(object sender, System.EventArgs e)
		{
			this.BackgroundColor = note.BackgroundColor;
			this.TextColor = note.TextColor;
            if (null!= note.ExtraFont)
                txtNote.Font = note.ExtraFont;
            else
                txtNote.Font = Properties.Settings.Default.Font;
			//WORKAROUND!
			//Hidden notes are loaded with form, but it is immediately hidden when loaded
			// this is 
            if ((note.HasAlarm) && (note.Hidden))
            {
                this.Opacity = 0.0;
            } 
            else if (note.Opacity != 1.0)
            {
                this.Opacity = note.Opacity;
            }
            else
                this.Opacity = Properties.Settings.Default.Opacity;

			Size s = this.ClientSize;
			Int32 wStyle = WinImports.GetWindowLong(this.Handle, WinImports.GWL_STYLE);
			int windowStyle = (int)wStyle; 
			windowStyle ^= WinImports.WS_CAPTION; 
			windowStyle ^= WinImports.WS_THICKFRAME; // Resizable frame is not really
			int old = WinImports.SetWindowLong(this.Handle, WinImports.GWL_STYLE, windowStyle);
			//Console.WriteLine("GWL_STYLE before change= {0}; after change= {1}.",old, windowStyle );
			// calculate how to position window so client area remains where it was before caption and border disappeared.
			borderSize = (this.Width - s.Width)/2;
			int captionHeight = this.Height - (s.Height + borderSize);
			bool ret = WinImports.SetWindowPos(this.Handle, this.Handle, note.Position.X, note.Position.Y, //this.Left + borderSize, this.Top + captionHeight,
				note.Position.Width, note.Position.Height, WinImports.SWP_NOZORDER | WinImports.SWP_FRAMECHANGED);
            
            // Wierd!?!?! For some reason if NoteForm is hidden then Height is bigger than 
            // saved and than set by SetWindowLong. Therefore here is extra set of Height prop.?!?!?!
            this.Height = note.Position.Height;
            // assign text either Rtf or plain text.
			TextEx = note.Text;
			
            this.TopMost = note.OnTop;

			// Workaround! URL is not normally detected when form is loaded. Reseting property helps.
			txtNote.DetectUrls = false;
			txtNote.DetectUrls = true;
            txtNote.Height = note.Position.Height - 2;
            //txtNote.Dock = DockStyle.Fill;

			if ((note.HasAlarm) && (note.Hidden))
				this.Opacity = Properties.Settings.Default.Opacity;
            else if (note.Opacity != 1.0)
            {
                this.Opacity = note.Opacity;
            }
            else
                this.Opacity = Properties.Settings.Default.Opacity;

            if (false == NoteData.DataHandler.OutlookOK)
                RemoveOutlookMenuItems();

            SetToolTipText();

            this.txtNote.TextChanged += new System.EventHandler(this.txtNote_TextChanged);
			this.Resize += new System.EventHandler(this.NoteForm_Resize);
            System.Console.WriteLine("OnLoad completed");
		}

        private void SetToolTipText()
        {
            
            if (DateTime.MinValue != note.LastModificationTime)
            {
                normalToolTip = string.Format(Resources.AppResource.LastModification, note.LastModificationTime.ToShortDateString(),
                    note.LastModificationTime.ToShortTimeString());
                toolTip.SetToolTip(txtNote, normalToolTip);
            }
        }

        /// <summary>
        /// Method removes Outlook related menu items when Outlook is not available.
        /// </summary>
        private void RemoveOutlookMenuItems()
        {
            this.mainMenu.Items.Remove(this.copyToOutlookStripMenuItem);
            //this.mainMenu.Items.Remove(this.emailStripMenuItem);
        }

        // TODO - When changing resizable/noresizable border there are still few pixels being added and removed.
        // Also, last selected desknote is on startup displayed lower than it was before app exit.

        /// <summary>
        /// Sets border to nonresizable thin border without caption and not shown in taskbar.
        /// </summary>
        internal void RemoveResizableBorder()
        {
            Int32 wStyle = WinImports.GetWindowLong(this.Handle, WinImports.GWL_STYLE);
            int windowStyle = (int)wStyle;
            int origWindowStyle = windowStyle;
            // Remove the THICKFRAME flag only if it is set
            if (0 != (windowStyle & WinImports.WS_THICKFRAME))
            {
                windowStyle ^= WinImports.WS_THICKFRAME;
            }
            if (0 != (windowStyle & WinImports.WS_CAPTION)){
                windowStyle ^= WinImports.WS_CAPTION;
            }
            // only if window style was changed then change window and its position
            if (windowStyle != origWindowStyle)
            {
                //Size s = this.ClientSize;
                int old = WinImports.SetWindowLong(this.Handle, WinImports.GWL_STYLE, windowStyle);
                //Console.WriteLine("Deactivated: {2}, old style={0}, new style={1}", old.ToString(),windowStyle.ToString(), this.note.Text.Substring(0, 5));
                bool ret = WinImports.SetWindowPos(this.Handle, this.Handle,note.Position.X, note.Position.Y, //this.Left, this.Top,
                    note.Position.Width, note.Position.Height, WinImports.SWP_NOZORDER | WinImports.SWP_FRAMECHANGED);
                tableLayoutPanel.Refresh();
                this.ShowInTaskbar = false;
                Console.WriteLine("RemoveResizableBorder:" + this.ClientSize);
            }
        }
				
		private void Clicked()
		{
            
			//Console.WriteLine("Clicked: " + txtNote.Text.Substring(0,5));
			Int32 wStyle = WinImports.GetWindowLong(this.Handle, WinImports.GWL_STYLE);
			int windowStyle = (int)wStyle;
            // If THICKFRAME is set then do nothing
            if (0 != (windowStyle & WinImports.WS_THICKFRAME))
            {
                return;
            }
            Size s = this.ClientSize;
            Console.WriteLine("Clicked, borderSize: " + borderSize);
            Console.WriteLine("Before SetWndPos, form;{0}, clientSize:{1}, txtNote:{2}.", this.Size, this.ClientSize, txtNote.Size);
			windowStyle = windowStyle | WinImports.WS_THICKFRAME;
            int old = WinImports.SetWindowLong(this.Handle, WinImports.GWL_STYLE, windowStyle);
            
            this.Left -= borderSize;
            this.Top -= borderSize;
            this.Width += 2 * borderSize;
            this.Height += 2 * borderSize;
            
			// Form can be used by mouse when it first enters the form.
            Console.WriteLine("After  SetWndPos, form:{0}, clientSize:{1}, txtNote:{2}.", this.Size, this.ClientSize, txtNote.Size);
			ReadyForMouse = true;
		}

		

		private void NoteForm_Deactivate(object sender, System.EventArgs e)
		{
			//Console.WriteLine("Deactivated; {0}, {1} ",  this.note.Text.Substring(0, 5), sendBack);
			// Send note back only when it is allowed.
			// Can be disabled during Archive window display and when systray icon is clicked.
			if (sendBack)
			{
				DeactivateForm();
			}
			sendBack = true;
		}

		protected void DeactivateForm()
		{
			//Console.WriteLine("Deactivated, " + txtNote.Text.Substring(0,3));
			//if ((!note.DataHandler.ShowingAllNotes) && (!this.note.OnTop))
			//	this.SendToBack();

			//necessary to properly paint withour border remaining on a control.
			tableLayoutPanel.Refresh();
			
			// When text was changed in a note then save it as well.
            SaveText();
			// when form was resized then save note as well.
			if ((FormResized) && (ReadyForMouse) && (!this.BoundsNoBorder.Equals(note.Position)))
			{
				note.Position = this.BoundsNoBorder;
			}
			//this.TopMost = note.OnTop;
			FormResized = false;

            RemoveResizableBorder();

			// Assur that topmost note which was put back at new note creation
			// becames topmost when newly created note is deactivated.
			if (topMostViolated)
			{
				topMostViolated = false;
				note.DataHandler.ConfirmTopMost();
			}
		}

        /// <summary>
        /// Getter for bounds of DeskNote without resizable border.
        /// </summary>
        Rectangle BoundsNoBorder
        {
            get
            {
                Int32 wStyle = WinImports.GetWindowLong(this.Handle, WinImports.GWL_STYLE);
                int windowStyle = (int)wStyle;
                // if there is thickframe around DeskNote then calculate bounds without it.
                if (0 != (windowStyle & WinImports.WS_THICKFRAME))
                {
                    //Console.WriteLine("FormBounds:{0},{1},{2},{3}", this.Left, this.Top, this.Width, this.Height);
                    //Console.WriteLine("Bounds:{0},{1},{2},{3}", this.Left + borderSize, this.Top + borderSize,
                    //this.Width - (2 * borderSize), this.Height - (2 * borderSize));

                    return new Rectangle(this.Left + borderSize, this.Top + borderSize,
                    this.Width - (2 * borderSize), this.Height - (2 * borderSize));
                }
                else
                { // Thickframe is not around DeskNote then return form bounds
                    return this.Bounds;
                }
            }
        }

		/// <summary>
		/// Method sets toolbar according to Alarm setting. If alarm is valid then timer is started.
		/// </summary>
		internal void SetAlarmToolbar()
		{
			// no alarm is set therefore it will not be displayed in show note mode.
			if (note.HasAlarm)
			{
				// show alarm toolbar.
                tableLayoutPanel.SetRow(txtNote, 1);
                tableLayoutPanel.SetRowSpan(txtNote, 1);
				panel.Visible = true;
				alarmTime.Text = note.AlarmText;
				alarmTime.Font = new Font(alarmTime.Font.Name, alarmTime.Font.Size,FontStyle.Regular);
				clockPicture.Show();
				alarmTime.Dock = DockStyle.None;
				//txtNote.Anchor = (AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom);
				//txtNote.Invalidate();
				
				if (note.Alarm < DateTime.Now)
				{
					SetAlarmOver();
					Reminded();
				} 
				else 
				{	//remove note from reminders window. Only if it was there already.
					RemoveReminded();
				}
			} 
			else 
			{ // hide alarm toolbar and fill all form with text box.
				panel.Visible = false;
				tableLayoutPanel.SetRow(txtNote, 0);
                tableLayoutPanel.SetRowSpan(txtNote, 2);
                RemoveReminded();
			}
		}

		/// <summary>
		/// Menu handler for Font ... menu item.
		/// Includes setting of text color as well.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		/* private void ChooseFont(object sender, System.EventArgs e)
		{
			fontDialog.Font = txtNote.Font;
			fontDialog.Color = note.TextColor;
			if (DialogResult.OK == fontDialog.ShowDialog())
			{
				txtNote.Font =  fontDialog.Font;
				note.ExtraFont = fontDialog.Font;
				note.TextColor = fontDialog.Color;
				this.TextColor = fontDialog.Color;
			}
		} */

		/// <summary>
		/// Menu handler for Set Alarm menu item.
		/// Sets alarm for given Desknote including text, icon and timer.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		internal void SetAlarm(object sender, System.EventArgs e)
		{
			AlarmDialog alarmDlg = new AlarmDialog();
			if (note.HasAlarm)
				alarmDlg.Alarm = note.Alarm;
			else
				alarmDlg.Alarm = DateTime.Now;

			if (DialogResult.OK == alarmDlg.ShowDialog(this))
			{
				note.Alarm = alarmDlg.Alarm;
				SetTimer();
				//show alarm in desknote
				SetAlarmToolbar();
			}
		}

		/// <summary>
		/// Method sets all timer properties according to this DeskNote alarm time.
		/// </summary>
		internal void SetTimer()
		{
			if ((note.HasAlarm) && (note.Alarm > DateTime.Now))
			{
				TimeSpan interval = note.Alarm - DateTime.Now;
				timer1.Interval = interval.TotalMilliseconds;
				timer1.Enabled = true;
			}
		}

		/// <summary>
		///  Menu handler for Reset Alarm menu item.
		///  Resets alarm: removes text, icon and stops timer.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void ResetAlarm(object sender, System.EventArgs e)
		{
			note.ResetAlarm();
			// Stop the timer in the form 
			timer1.Enabled = false;
			SetAlarmToolbar();
		}

		/// <summary>
		/// Calls exit delegate from DeskNotes class which handles all the cleanup.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void Exit_Clicked(object sender, System.EventArgs e)
		{
            SaveText();
			note.DataHandler.Exit();
		}

		private void MoveStart_OnMouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (e.Clicks > 0)
			{
				Clicked();
			}
			if (Archiving)
			{
				mouseX = e.X ;
				mouseY = e.Y;
				dragging = false;
				//this.Cursor = Cursors.Hand;
				Size dragSize = SystemInformation.DragSize;

				dragRect = new Rectangle(new Point(e.X - (dragSize.Width /2),
					e.Y - (dragSize.Height /2)), dragSize);
			}
			else 
				if (ControlDown && (e.Button == MouseButtons.Left))
				{
					mouseX = e.X ;
					mouseY = e.Y;
					beforeMoveCursor = this.Cursor;
					this.Cursor = Cursors.Hand;
					txtNote.ReadOnly = true;
				}
		}

		private void MoveEnd_onMouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (Archiving)
			{
				Archiving = false;
			} else
				if (ControlDown && (e.Button == MouseButtons.Left))
				{
					int x = this.Left + e.X;
					this.Left = x - mouseX;
					int y = this.Top + e.Y;
					this.Top = y - mouseY;
					this.Cursor = beforeMoveCursor;
					txtNote.ReadOnly = false;
					if (WasMoved)
					{
						note.Position = new Rectangle(this.Left, this.Top, this.Width, this.Height);
					}
					WasMoved = false;
					
				}
		}

       
		private void NoteForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			ControlDown = e.Control;
            if (e.Control) {
               // System.Console.WriteLine("Keycode: " + e.KeyCode);
                switch (e.KeyCode)
                {
                    case Keys.B:
                        if (e.Shift)
                        { // Ctrl+Shift+B makes line bullet
                            this.btnBullet_Click(sender, null);
                        }
                        else
                        {
                            this.btnBold_Click(sender, null);
                        }
                        break;
                    case Keys.I: 
                        this.btnItalic_Click(sender, null);
                        // SuppressKeyPress has to be called because some unknown maybe native control code interprets this
                        // as insert "\t" into text box.
                        e.SuppressKeyPress = true;
                        break;
                    case Keys.U:
                        this.btnUnderline_Click(sender, null);
                        break;
                    case Keys.S:
                        this.menuSave_Click(sender, null);
                        break;
                    case Keys.Oemcomma:
                        this.btnIndentLeft_Click(sender, null);
                        break;
                    case Keys.OemPeriod:
                        this.btnIndentRight_Click(sender, null);
                        break;
                    case Keys.C: // copy to Clipboard as plain text
                        Clipboard.SetText(txtNote.SelectedText, TextDataFormat.UnicodeText);
                        e.SuppressKeyPress = true;
                        break;
                    case Keys.X: //Cut to Clipboard as plain text
                        string text = txtNote.SelectedText;
                        string note = txtNote.Text;
                        int selection = txtNote.SelectionStart;
                        txtNote.Text = note.Substring(0, txtNote.SelectionStart) +
                            note.Substring(txtNote.SelectionStart + txtNote.SelectionLength, 
                                note.Length - (txtNote.SelectionLength+txtNote.SelectionStart));
                        Clipboard.SetText(text, TextDataFormat.UnicodeText);
                        e.SuppressKeyPress = true;
                        if (selection < txtNote.Text.Length)
                            txtNote.SelectionStart = selection;
                        break;
                    case Keys.V: //Paste text as plain text
                        if (Clipboard.ContainsText())
                        {
                            txtNote.SelectedText = Clipboard.GetText();
                            e.SuppressKeyPress = true;
                        }
                        break;
                 }
             }
		}

		/// <summary>
		/// Checks for Control key and Esc during archivation
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void NoteForm_KeyUp(object sender, System.Windows.Forms.KeyEventArgs e)
		{
			ControlDown = e.Control;
			if ((Archiving) && (e.KeyCode == Keys.Escape))
			{
				DragDropDone();
			}
		}

		private void NoteForm_MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (Archiving)
			{   //archiving is in progress
				// check if dragging really started
				if ((!dragging) && ((dragRect != Rectangle.Empty) && 
					(!dragRect.Contains(e.X, e.Y))))
				{
					dragging = true;
					this.DoDragDrop(this.note, DragDropEffects.Move);
				}
			}
			else // Moving deskNotes on desktop, no dragging/archiving.
				if (ControlDown && (e.Button == MouseButtons.Left))
			{
				WasMoved = true;
				int x = this.Left + e.X;
				this.Left = x - mouseX;
				int y = this.Top + e.Y;
				this.Top = y - mouseY;
			}
		}

		private void txtNote_TextChanged(object sender, System.EventArgs e)
		{
			textChanged = true;
		}

		private void NoteForm_Resize(object sender, System.EventArgs e)
		{
			FormResized = true;
            Size s = this.ClientSize;
            txtNote.Width = s.Width - 2;
			// resize txtNote text field according to new size of form.
			// do it only when alarm is displayed as this is the time when
            // Dock is not set to Fill.
            txtNote.Height = s.Height - 2;
			if (note.HasAlarm)
			{
				txtNote.Height = txtNote.Height - panel.Height;
			}
		}

		/// <summary>
		/// Menu handler for "New" menu item. Creates new desknote over this one. If "this" is TopMost 
		/// then its TopMost status is reseted until user deactivates newly created desknote.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void CreateNewNote(object sender, System.EventArgs e)
		{
			Note n = note.DataHandler.CreateNewNote(MainResource.GetString("FIRST_NOTE"), new Rectangle(this.Left+20, this.Top+10, this.Width, this.Height));
			if (note.OnTop) 
			{
				this.TopMost = false;
				n.MyForm.topMostViolated = true;
			}
			n.MyForm.Activate();
		}

		/// <summary>
		/// Removes DeskNote from desktop and data from dataset as well.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		internal void menuRemove_Click(object sender, System.EventArgs e)
		{
			try 
			{
				note.RemoveRecord();
                this.Deactivate -= new System.EventHandler(this.NoteForm_Deactivate);
				this.Close();
			}
			catch (Exception ex)
			{
				MessageBox.Show(this, MainResource.GetString("ERROR_REMOVE") + ex.Message,
					MainResource.GetString("APP_TITLE"), MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		

		/// <summary>
		/// Sets alarm that it indicates the time is over.
		/// It hides clock picture and atrike out the time on label.
		/// </summary>
		private void SetAlarmOver()
		{
			clockPicture.Hide();
			alarmTime.Dock = DockStyle.Left;
			alarmTime.Font = new Font(alarmTime.Font.Name, alarmTime.Font.Size,FontStyle.Strikeout); 
		}

        private void mainMenu_Opening(object sender, CancelEventArgs e)
        {
            if (note.HasAlarm)
                removeReminderStripMenuItem.Visible = true;
            else
                removeReminderStripMenuItem.Visible = false;

            if (note.OnTop)
                alwaysOnTopStripMenuItem.Checked = true;
            else
                alwaysOnTopStripMenuItem.Checked = false;
            if (null != note.OutlookEntryID)
            {
                copyToOutlookStripMenuItem.Text = Resources.AppResource.OutlookSync;
            }
        }
		

		

		/// <summary>
		/// Handler for click on link in the DeskNote. Links are recognized for all internet
		/// protocols and for file:/// also.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void txtNote_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e)
		{
			try
			{
				System.Diagnostics.Process.Start(e.LinkText);
			}
			catch (Exception ex)
			{
				MessageBox.Show(this, MainResource.GetString("CANNOT_OPEN_LINK") + ex.Message, MainResource.GetString("APP_TITLE"),
					MessageBoxButtons.OK,MessageBoxIcon.Exclamation);
			}
		}

		/// <summary>
		/// Sets background color of given Desknote
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuColor_Click(object sender, System.EventArgs e)
		{
			colorDialog.Color = this.BackgroundColor;
			if (DialogResult.OK == colorDialog.ShowDialog())
			{
				this.BackgroundColor = colorDialog.Color;
				note.BackgroundColor = colorDialog.Color;
			}
		}
		/// <summary>
		/// Method set TopMost forms property but befero enabling it on current 
		/// note this has to be removed from previous one if set there.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuAlwaysOnTop_Click(object sender, System.EventArgs e)
		{
            if (note.OnTop)
            {  // Desknote is top most selecting the menu means it is no longer topmost.
                note.OnTop = false;
                this.TopMost = false;
            }
            else
            {  // DeskNote is becoming top most note.
                note.DataHandler.ResetCurrentTopMost();
                note.OnTop = true;
                this.TopMost = true;
            }
            alwaysOnTopStripMenuItem.Checked = note.OnTop;
		}

		private void menuHide_Click(object sender, System.EventArgs e)
		{
			note.Hidden = true;
		}

		
		private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
		{
			// Call Alarmed method to handle form show after alarm elapsed
			Invoke(invocation);
		}

		/// <summary>
		/// Time over handler for desknotes reminder.
		/// It creates notification form and displays it.
		/// </summary>
		internal void Alarmed()
		{
			timer1.Enabled = false;
			note.PlaySound();

            string text = note.PlainText;
            text = text.Length > 70 ? text.Substring(0,70)+ "..." : text;
			text = string.Format(MainResource.GetString("NOTE_IS_DUE"), alarmTime.Text, "\n", text);
			
			NotifyForm notification = new NotifyForm();
			notification.NoteText = text;
			notification.StartNotification(new NotifyActionHandler(HandleNotifyAction));
		}

		/// <summary>
		/// Handles user interaction from NotifyForm.
		/// When text was clicked then it activates this desknote. 
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		internal void HandleNotifyAction( object sender, NotifyActionEventArgs args )
		{
			// when closed or just un noticed then strike through alarm time
			switch(args.NotifyAction)
			{
				case NotifyForm.Action.Closed:
				{
					this.SetAlarmOver();
					ShowMeIndirectly(null,null);
					note.DataHandler.ConfirmTopMost();
					//this.Activate();
					this.BringToFront();
				} break;
				case NotifyForm.Action.Selected: 
				{	//Notify text was selected then remove alarm completely
					ResetAlarm(this, null);
					ShowMeIndirectly(null,null);
					note.DataHandler.ConfirmTopMost();
					this.BringToFront();
				} break;
				case NotifyForm.Action.Missed:
				{ //Set alarm over, but invent better user solution.
					this.SetAlarmOver();
					Reminded();
				} break;
			}
		}


		/// <summary>
		/// Adds note to Missed reminders window
		/// </summary>
		private void Reminded()
		{
			RemindersForm reminders = note.DataHandler.RemindersWindow;
			if (null == remindersItem)
				remindersItem = reminders.AddNote(note);
		}

		/// <summary>
		/// Remove note from missed Reminders window.
		/// </summary>
		private void RemoveReminded()
		{
			if (null != remindersItem)
			{
				RemindersForm reminders = note.DataHandler.RemindersWindow;
				reminders.RemoveNote(remindersItem);
				remindersItem = null;
			}
		}

		/// <summary>
		/// Handles user action made over note displayed at missed reminders window - RemindersForm
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		internal void HandleRemindersAction(object sender, RemindersActionEventArgs args)
		{
			if (RemindersForm.Action.Closed == args.PostReminderAction)
			{
				remindersItem = null;
			} 
			else if (RemindersForm.Action.Open == args.PostReminderAction)
			{
				this.ShowMeIndirectly(this, null);
			}
			else if (RemindersForm.Action.Dismiss == args.PostReminderAction)
			{
				this.NoteData.ResetAlarm();
				this.SetAlarmToolbar();
				remindersItem = null;
			}
		}

		/// <summary>
		/// Overriden Form.Show(). Show performs proper placement 
		/// on screen if screen resolution changed.
		/// </summary>
		new public void Show()
		{
			Int32 wStyle = WinImports.GetWindowLong(this.Handle,WinImports.GWL_EXSTYLE);
			int windowStyle = (int)wStyle;
			if (0!= (windowStyle & WinImports.WS_EX_APPWINDOW))
			{
				windowStyle ^= WinImports.WS_EX_APPWINDOW;
				int old = WinImports.SetWindowLong(this.Handle, WinImports.GWL_EXSTYLE, windowStyle);
				//Console.WriteLine("Show; GWL_EXSTYLE before change= {0}; after change= {1}.",old, windowStyle );
			}
			base.Show();
			CheckPositionOnScreen();
		}

		/// <summary>
		/// Override Form.Activate(). Performs check for screen size 
		/// during activation and repositions desknote if it's outside of screen.
		/// </summary>
		new public void Activate()
		{
			base.Activate();
			this.CheckPositionOnScreen();
		}


		/// <summary>
		/// Moves form to visible part of screen if it is being displayed
		/// outside of screen visible area. Can happen when switching displays.
		/// </summary>
		private void CheckPositionOnScreen()
		{
			Size workingArea = SystemInformation.WorkingArea.Size;
			int x = this.Left;
			int y = this.Top;

			//check position at righ and bottom of the screen
			if (workingArea.Width < this.Left) 
				x = workingArea.Width - this.Size.Width;
			else if ((this.Left + this.Width) < 5)
				x = 5;
			
			if (workingArea.Height < this.Top)
				y = workingArea.Height - this.Size.Height;
			else if (this.Top + this.Height < 5 )
				y = 5;

			this.SetDesktopLocation(x, y);
		}

		/// <summary>
		/// This method activates Desknote when its menu item is 
		/// clicked at MainForm systray icon popup menu.
		/// It is set dynamically for each particular desknote when menu items are added 
		/// to the icon popup menu.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		internal void ShowMeIndirectly(Object sender, EventArgs e)
		{
			if (note.Hidden)
			{
				note.Hidden = false;
				Show();
			}
			else 
			{
				 //Activate();
                BringToFront();
			}	
			//set sizable border
			this.Clicked();
		}

        /// <summary>
        /// Shows transparent copy of desknote that was hovered in context menu.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void ShowMyCopy(Object sender, EventArgs e)
        {
            myCopy = new NoteForm();
            //Note tempNote = new Note(0, note.Text, new Rectangle(this.Left,this.Top,this.Width, this.Height), this.backgroundColor, this.textColor);
            myCopy.NoteData = this.NoteData;
            //myCopy.Owner = (Form)sender;
            myCopy.Show();
            myCopy.Opacity = 0.1;
        }

        /// <summary>
        ///  Hides transparent copy after some time or when focused menu changes.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void HideMyCopy(Object sender, EventArgs e)
        {
            /*if (null != myCopy)
            {
                myCopy.Close();
                myCopy = null;
            }*/

        }
		

		private void menuPrint_Click(object sender, System.EventArgs e)
		{
			try {
				note.DataHandler.PrintOneNote(note,(ToolStripMenuItem) sender);
			} 
			catch (System.Drawing.Printing.InvalidPrinterException ex)
			{
				MessageBox.Show(this, string.Format(MainResource.GetString("PRINTER_NOT_AVAILABLE"), ex.Message), MainResource.GetString("APP_TITLE"),
					MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}


		/// <summary>
		/// DeskNote form cannot be closed by Alt+F4. It will cancel the event
		/// and hide the form instead.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void NoteForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
		{
			e.Cancel = true;
			note.Hidden = true;
		}

		/// <summary>
		/// Mouse_Leave is used to determine if mouse moved to another window, potentially overlapping over 
		/// the note, WITHOUT clicking into this window. It is used to reset note from activeted state 
		/// into deactivated (flat) state. The problem remains with editing (I-beam) cursor inside 
		/// txtNote richtext box which remains blinking there. Does not know how to solve it??!?!?!
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void NoteForm_MouseLeave(object sender, System.EventArgs e)
		{
			//Console.WriteLine("MouseLeave; " +  txtNote.Text.Substring(0,3));
			IntPtr foregroundWindow = WinImports.GetForegroundWindow();
			if (foregroundWindow != this.Handle)
			{
				////Console.WriteLine("Mouse is over another window:" + foregroundWindow.ToString());
				
				DeactivateForm();					
			}
		}

		/// <summary>
		/// Start archive action. If Drag&Drop is defined then it initiates it.
		/// When Archive as simple action is set then archive is performed.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuArchive_Click(object sender, System.EventArgs e)
		{	
			//Save changes to text first
            SaveText();
			
			if (note.DataHandler.LoadArchive()) 
			{
				ArchiveForm archForm = note.DataHandler.archiveForm;
				if ( null == archForm)
				{
					archForm = new ArchiveForm(note.DataHandler);
				}
				if ((FormWindowState.Maximized == archForm.WindowState)
					|| (FormWindowState.Minimized == archForm.WindowState))
				{
					archForm.WindowState = FormWindowState.Normal;
				}
				sendBack = false;
				archForm.Show();
				archForm.Activate();
				if (Properties.Settings.Default.DragDropToArchive)
				{ // Archive by drag drop.
					Archiving = true;
					this.Refresh();
				}
				else
 				{ 
					// Archive by calling archive form method
					archForm.Archive(this.note);
				}
			}
			sendBack = true;
		}

		/// <summary>
		/// Sets proper state of NoteForm UI when archiving and when 
		/// archiving was cancelled.
		/// </summary>
		private bool Archiving{
			set
			{
				if (value == true)
				{
					toolTip.SetToolTip(this.txtNote, MainResource.GetString("ARCHIVATION_TIP"));
					Cursor = Cursors.Hand;
					txtNote.Cursor = Cursors.Hand;
					clockPicture.Cursor = Cursors.Hand;
					alarmTime.Cursor = Cursors.Hand;
				}
				else 
				{
					toolTip.SetToolTip(txtNote, normalToolTip);
					Cursor = Cursors.Arrow;
					txtNote.Cursor = Cursors.IBeam;
					clockPicture.Cursor = Cursors.Arrow;
					alarmTime.Cursor = Cursors.Arrow;
				}
				archiving = value;
			}
			get 
			{
				return archiving;
			}
		}

		private void NoteForm_QueryContinueDrag(object sender, System.Windows.Forms.QueryContinueDragEventArgs e)
		{
			//Console.WriteLine("QueryContinueDrag, Sender: {0}, Action: {1}.", sender.ToString(), e.Action.ToString());
			if ((e.EscapePressed) || (e.Action == DragAction.Cancel))
			{
				DragDropDone();
			} 
			else if (e.Action == DragAction.Drop)
			{
				// desknote dropped into archive
				DragDropDone();
			}
		}

		/// <summary>
		/// Reset all the flags used in form archivation using drag&drop
		/// </summary>
		private void DragDropDone()
		{
			Archiving = false;
			dragging = false;
			dragRect = Rectangle.Empty;
		}

		/// <summary>
		/// Inserts current date and time into cursor position at text
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuInsertTime_Click(object sender, System.EventArgs e)
		{
            System.Text.StringBuilder timeStamp = new System.Text.StringBuilder(note.DataHandler.TimeStamp);
            timeStamp.Insert(0, "\n");
            timeStamp.Append("\n");
            txtNote.SelectedText = timeStamp.ToString();
		}

		
				
		/// <summary>
		/// Form property which sets appropriate background 
		/// for all components on a form
		/// </summary>
		public Color BackgroundColor
		{
			set 
			{
				this.BackColor = value;
				tableLayoutPanel.BackColor = value;
				txtNote.BackColor = value;
				alarmTime.BackColor = value;
			}
			get 
			{
				return this.BackColor;
			}
		}

		/// <summary>
		/// Text color property for a given DeskNote form and all its components.
		/// </summary>
		public Color TextColor 
		{
			set 
			{
				txtNote.ForeColor = value;
				alarmTime.ForeColor = value;
			}
		}

        /// <summary>
        /// Text assigned to note displayed on DeskNote RichTextBox
        /// Set - plain text or RTF text
        /// Get - plain text only
        /// </summary>
        internal string TextEx
        {
            get
            {
                return txtNote.Text;
            }

            set
            {
                if (value.StartsWith(RtfConverter.RTF_TAG))
                    txtNote.Rtf = value;
                else
                    txtNote.Text = value;
            }
        }

        /// <summary>
        /// Rtf formatted string displayed inside this DeskNote
        /// </summary>
        internal string Rtf
        {
            get { return txtNote.Rtf; }
        }

        /// <summary>
        /// Makes sure text is saved including latest updates to it.
        /// This is necessary as text changes are propagated usually after desknote looses focus,...
        /// </summary>
        private void SaveText()
        {
            if (textChanged)
            {
                note.LastModificationTime = System.DateTime.Now;
                note.Text = txtNote.Rtf; // txtNote.Text;
                textChanged = false;
                SetToolTipText();
            }
        }
        /// <summary>
        /// Performs emailing action. If Outlook is available then it uses Outlook though its API, it has 
        /// better formatting options. Otherwise ShellExecute action "mailto" is invoked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuEmail_Click(object sender, EventArgs e)
        {
            try {
                if (note.DataHandler.OutlookOK)
                { // if outlook can email then use it as it has better formatting.
                    Outlook.Application olApp = new Outlook.Application();
                    Outlook.MailItem email = (Outlook.MailItem)olApp.CreateItem(Outlook.OlItemType.olMailItem);
                    email.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatPlain;
                    email.Subject = Resources.AppResource.EMAIL_SUBJECT;
                    SaveText();
                    email.Body = TextEx; // assigns plain text from desknote
                    email.Display(false);
                }
                else
                {
                    System.Text.StringBuilder sMail = new System.Text.StringBuilder(TextEx.Length + 100);
                    sMail.Append("mailto:?Subject=");
                    sMail.Append(Resources.AppResource.EMAIL_SUBJECT);
                    sMail.Append("&Body=");
                    sMail.Append(TextEx);
                    WinImports.ShellExecute(this.Handle, "open", sMail.ToString(), null, null, 1);
                }
           }catch (Exception ex){
                string msg = string.Format(Resources.AppResource.EMAIL_ERROR,ex.Message);
                MessageBox.Show(this, msg, Resources.AppResource.APP_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                note.DataHandler.OutlookOK = false;
            }
        }

        /// <summary>
        /// Method saves DeskNotes text into Outlook Notes or updates the 
        /// text in a Outlook Note up to DeskNotes note. One way syncronization.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSaveInOutlook_Click(object sender, EventArgs e)
        {
            //Outlook is not ready then exit.
            if (false == NoteData.DataHandler.OutlookOK)
                return;
            try
            {
                SaveText();
                SynchronizationConflictDlg.Result r = SynchronizationConflictDlg.Result.SyncOne;
                if (SynchronizationConflictDlg.Result.OutlookMissing == NoteData.SynchronizeOutlook(this, ref r))                  
                {
                    MessageBox.Show(this, Resources.AppResource.OutlookCopyRemoved, Resources.AppResource.APP_TITLE,
                           MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    this.copyToOutlookStripMenuItem.Text = Resources.AppResource.OutlookCopy;
                }
                // all changes done during synchronization does not need another change.
                textChanged = false;
            }
            catch (Exception ex)
            {
                // Show error dialog for Outlook integration
                MessageBox.Show( this, Resources.AppResource.OutlookError + ex.Message, Resources.AppResource.APP_TITLE,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                NoteData.DataHandler.OutlookOK = false;
            }
        }

        /// <summary>
        /// NoteForm own change of Opacity. Invokes Opacity Dialog when it is closed by OK it
        /// compares the values and if current and new values differ then it sets opacity for current Desknote.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuOpacity_Click(object sender, EventArgs e)
        {
            OpacityDialog dlg = new OpacityDialog();
            int iOpacity = (int) (this.Opacity * 100);
            dlg.lblOpacity.Text = iOpacity + "%";
            dlg.trackBar.Value = iOpacity;
            if (DialogResult.OK == dlg.ShowDialog(this))
            {
                //Better to compare integers than doubles for opacity it is enough accurate.
                int newOpacity = dlg.trackBar.Value;
                if (newOpacity != iOpacity)
                {
                    note.Opacity = (double)newOpacity;
                    note.Opacity /= 100;
                    this.Opacity = note.Opacity;
                    this.RemoveResizableBorder();
                }
            }
        }

        /// <summary>
        /// Save Desknote on demand not just when it looses focus.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSave_Click(object sender, EventArgs e)
        {
            //remember position and reset its trackers
            note.Position = this.BoundsNoBorder;
            FormResized = false;
			WasMoved = false;
            //Saves text also as setting Text property writes XML to disk
            SaveText();
            //Saves desknote and all its properties.
            note.Save();
        }

        /// <summary>
        /// Shos editing toolbar inside desknote.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuEdit_Click(object sender, EventArgs e)
        {
            if (this.formattingStripMenuItem.Checked)
                CompletedEditing();
            else
                StartEditing();
            formattingStripMenuItem.Checked = !formattingStripMenuItem.Checked;
        }

        private void StartEditing()
        {
            toolStripRTF.Show();
        }

        private void CompletedEditing()
        {
            toolStripRTF.Hide();
        }

        /// <summary>
        /// Change Bullet style for current selection
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBullet_Click(object sender, EventArgs e)
        {
            txtNote.SelectionBullet = ! txtNote.SelectionBullet;
            textChanged = true;
           
        }

        private void txtNote_SelectionChanged(object sender, EventArgs e)
        {
            btnBullet.Checked = txtNote.SelectionBullet;
            if (null != txtNote.SelectionFont)
            {
                btnBold.Checked = txtNote.SelectionFont.Bold;
                btnItalic.Checked = txtNote.SelectionFont.Italic;
                btnStrike.Checked = txtNote.SelectionFont.Strikeout;
                btnUnderline.Checked = txtNote.SelectionFont.Underline;
            }
        }

        private void btnBold_Click(object sender, EventArgs e)
        {
            Font f  = txtNote.SelectionFont;
            Font newFont;
            if (f.Bold)
                newFont = new Font(f, f.Style ^ FontStyle.Bold );
            else
                newFont = new Font(f, f.Style | FontStyle.Bold);
            txtNote.SelectionFont = newFont;
            btnBold.Checked = newFont.Bold;
            textChanged = true;
        }

        private void btnItalic_Click(object sender, EventArgs e)
        {
            Font f = txtNote.SelectionFont;
            Font newFont;
            if (f.Italic)
                newFont = new Font(f, f.Style ^ FontStyle.Italic);
            else
                newFont = new Font(f, f.Style | FontStyle.Italic);
            txtNote.SelectionFont = newFont;
            btnItalic.Checked = newFont.Italic;
            textChanged = true;
        }

        private void btnStrike_Click(object sender, EventArgs e)
        {
            Font f = txtNote.SelectionFont;
            Font newFont;
            if (f.Strikeout)
                newFont = new Font(f, f.Style ^ FontStyle.Strikeout);
            else
                newFont = new Font(f, f.Style | FontStyle.Strikeout);
            txtNote.SelectionFont = newFont;
            textChanged = true;
        }

        private void btnUnderline_Click(object sender, EventArgs e)
        {
            Font f = txtNote.SelectionFont;
            Font newFont;
            if (f.Underline)
                newFont = new Font(f, f.Style ^ FontStyle.Underline);
            else
                newFont = new Font(f, f.Style | FontStyle.Underline);
            txtNote.SelectionFont = newFont;
            btnUnderline.Checked = newFont.Underline;
            textChanged = true;
        }

        private void btnIndentRight_Click(object sender, EventArgs e)
        {
            txtNote.SelectionIndent += INDENT;
        }

        private void btnIndentLeft_Click(object sender, EventArgs e)
        {
            if (txtNote.SelectionIndent >= INDENT)
                txtNote.SelectionIndent -= INDENT;
        }

        /// <summary>
        /// Opens font dialog for current selection font.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFont_Click(object sender, EventArgs e)
        {
            fontDialog.Font = txtNote.SelectionFont;
            fontDialog.Color = txtNote.SelectionColor;
            if (DialogResult.OK == fontDialog.ShowDialog())
            {
                txtNote.SelectionFont = fontDialog.Font;
                txtNote.SelectionColor = fontDialog.Color;
            }
        }

        private void btnBackColor_Click(object sender, EventArgs e)
        {
            colorDialog.Color = this.BackgroundColor;
            if (DialogResult.OK == colorDialog.ShowDialog())
            {
                this.BackgroundColor = colorDialog.Color;
                note.BackgroundColor = colorDialog.Color;
            }
        }

        /// <summary>
        /// Changes color, font and fore color to defaults
        /// </summary>
        internal void ResetAppearance()
        {
            txtNote.Text = "";
            this.BackgroundColor = note.BackgroundColor;
            this.TextColor = Properties.Settings.Default.TextColor;
            txtNote.Font = Properties.Settings.Default.Font;
        }

       

       
    }
}
